<template>
  <!-- 上拉加载
    1：滚动条距离底部一定距离调用接口加载 onReachBottom
       pages.json配制距离参数
       onReachBottom调用接口
    2：数据是累加渲染
    3：加载 时分页（页码++）
    4:要判断数据是否加载完成
    5：正在加载过程中或者已全部加载完成是不允许再次加载 
    
    下拉刷新
    1：pages.json
         enablePullDownRefresh:true
    2:加入onPullDownRefresh方法
    3：方法内：
       a:所有数据还原成初始值
       b:调用相应接口（初始调用的接口）
       c:停止下拉刷新    
    -->
  <view class="list">
    <my-goods @click.native="goDetail(item.goods_id)" v-for="item in list" :key="item.goods_id" :item="item"></my-goods>
    <view class="end" v-if="finished">没有更多了</view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        list: [],
        query: '',
        page: 1,
        finished: false,
        loading: false // 是否正在加载中
      };
    },
    onLoad({
      key
    }) {
      // console.log('参数值', key);
      this.query = key
      this.goodsSearch()
    },
    async onPullDownRefresh() {
      console.log('onPullDownRefresh');
      this.list = []
      this.page = 1
      this.finished = false
      this.loading = false
      console.log(111);
      await this.goodsSearch()
      console.log(222);
      uni.stopPullDownRefresh()
    },
    onReachBottom() {
      console.log('距离底部100时触发了该方法');
      if (this.finished || this.loading) {
        return
      }
      this.page++
      this.goodsSearch()
    },
    methods: {
      async goodsSearch() {
        this.loading = true
        const res = await uni.$http.get('/goods/search', {
          params: {
            query: this.query,
            pagenum: this.page,
            pagesize: 10
          }
        })
        this.loading = false
        // 累加
        this.list.push(...res.message.goods)
        // 判断是否加载完成
        if (this.list.length >= res.message.total) {
          this.finished = true
        }
        console.log(333);


      },
      // 跳转至详情
      goDetail(id) {
        uni.navigateTo({
          url: "/pages/goods_detail/main?goods_id=" + id
          // navigateTo
          // switchTab
          // redirectTo
          // reLanch
          // navigateBack
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .list {

    .end {
      text-align: center;
      color: red;
    }
  }
</style>